
#include "global_avg_pool_tiling.h"
#include "register/op_def_registry.h"
#include "tiling/platform/platform_ascendc.h"
#include <algorithm>

namespace optiling {
static ge::graphStatus TilingFunc(gert::TilingContext* context)
{

    GlobalAvgPoolTilingData tiling;
    auto shape_x = context->GetInputTensor(0)->GetOriginShape();
    int32_t size;
    int32_t N;
    int32_t C;
    int32_t HW = 1;
    float firstDimValueBack;

    N = shape_x.GetDim(0);
    C = shape_x.GetDim(1);

    for(int i = 2; i < shape_x.GetDimNum(); i++)
        HW *= shape_x.GetDim(i);

    firstDimValueBack = float(1.0)/HW;

    tiling.set_size(N*C*HW);
    tiling.set_N(N);
    tiling.set_C(C);
    tiling.set_HW(HW);
    tiling.set_firstDimValueBack(firstDimValueBack);


    uint64_t ubSize;
    auto ascendcPlatform = platform_ascendc::PlatformAscendC(context->GetPlatformInfo());
    ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ubSize); //获取硬件平台存储空间 UB 的内存大小

    int32_t ub_size = ubSize / 4 / 3 / 32 * 32;
    tiling.set_ub_size(ub_size);
    

    context->SetBlockDim(1);
    tiling.SaveToBuffer(context->GetRawTilingData()->GetData(), context->GetRawTilingData()->GetCapacity());
    context->GetRawTilingData()->SetDataSize(tiling.GetDataSize());
    return ge::GRAPH_SUCCESS;
}
}


namespace ge {
static ge::graphStatus InferShape(gert::InferShapeContext* context)
{
    const gert::Shape* x1_shape = context->GetInputShape(0);
    gert::Shape* y_shape = context->GetOutputShape(0);
    *y_shape = *x1_shape;
    return GRAPH_SUCCESS;
}
}


namespace ops {
class GlobalAvgPool : public OpDef {
public:
    explicit GlobalAvgPool(const char* name) : OpDef(name)
    {
        this->Input("x")
            .ParamType(REQUIRED)
            .DataType({ge::DT_FLOAT, ge::DT_FLOAT16})
            .Format({ge::FORMAT_ND, ge::FORMAT_ND})
            .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
        this->Output("y")
            .ParamType(REQUIRED)
            .DataType({ge::DT_FLOAT, ge::DT_FLOAT16})
            .Format({ge::FORMAT_ND, ge::FORMAT_ND})
            .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});

        this->SetInferShape(ge::InferShape);

        this->AICore()
            .SetTiling(optiling::TilingFunc);
        this->AICore().AddConfig("ascend310b");

    }
};

OP_ADD(GlobalAvgPool);
}
